package ngames.com.sushitv.tools;

import android.content.Context;
import android.content.SharedPreferences;

import ngames.com.sushitv.entity.UserInfo;

/**
 * Created by Jeffrey on 2016/8/4.
 */
public class PreferenceManager {
    public static final String PREFERENCE_NAME = "appInfo";

    private static final String KEY_FIRST_OPEN_APP = "KEY_FIRST_OPEN_APP";
    private static final String KEY_TOKEN = "KEY_TOKEN";
    private static final String KEY_REFRESH_TOKEN = "KEY_REFRESH_TOKEN";
    private static final String KEY_EXPIRED = "KEY_EXPIRED";
    private static final String KEY_ACCOUNT_TYPE = "KEY_ACCOUNT_TYPE";
    private static final String KEY_SMS_TIME = "KEY_SMS_TIME";

    private static PreferenceManager mPreferenceManager;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    private PreferenceManager(Context cxt) {
        mSharedPreferences = cxt.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();
    }

    public static synchronized void init(Context cxt){
        if(mPreferenceManager == null){
            mPreferenceManager = new PreferenceManager(cxt);
        }
    }

    /**
     * 单例模式，获取instance实例
     * @return
     */
    public synchronized static PreferenceManager getInstance() {
        if (mPreferenceManager == null) {
            throw new RuntimeException("please init first!");
        }
        return mPreferenceManager;
    }

    public boolean isFirstOpenApp() {
        return mSharedPreferences.getBoolean(KEY_FIRST_OPEN_APP, true);
    }

    public void setHaveOpenApp() {
        mEditor.putBoolean(KEY_FIRST_OPEN_APP, false);
        mEditor.commit();
    }

    public void saveLoginInfo(UserInfo userInfo) {
        mEditor.putString(KEY_TOKEN, userInfo.getToken());
        mEditor.putString(KEY_REFRESH_TOKEN, userInfo.getRefreshToken());
        mEditor.putLong(KEY_EXPIRED, userInfo.getExpired());
        mEditor.putString(KEY_ACCOUNT_TYPE, userInfo.getAccountType());
        mEditor.commit();
    }

    public UserInfo getLoginInfo() {
        UserInfo userInfo = new UserInfo();
        userInfo.setToken(mSharedPreferences.getString(KEY_TOKEN, ""));
        userInfo.setRefreshToken(mSharedPreferences.getString(KEY_REFRESH_TOKEN, null));
        userInfo.setExpired(mSharedPreferences.getLong(KEY_EXPIRED, 0));
        userInfo.setAccountType(mSharedPreferences.getString(KEY_ACCOUNT_TYPE, null));
        return userInfo;
    }

    public void saveSmsTime(String key, String time) {
        mEditor.putString(KEY_SMS_TIME + key, time);
        mEditor.commit();
    }

    public String getSmsTime(String key) {
        return mSharedPreferences.getString(KEY_SMS_TIME + key, null);
    }
}
